<template>
  <div class="app-container">
    <!-- 步骤条 -->
    <el-steps
      :active="activeStep"
      finish-status="success"
      style="margin-bottom: 20px"
      align-center
    >
      <el-step title="生成核查系数"></el-step>
      <el-step title="确认客户应收"></el-step>
    </el-steps>
    <div style="margin: 32px 0">
      <!-- 步骤一：生成核查系数 -->
      <div v-show="activeStep === 0">
        <!-- 查询表单 -->
        <el-form :inline="true" :model="checkQuery" class="query-form" @submit.prevent>
          <el-form-item label="年份" prop="year">
            <el-date-picker
              v-model="checkQuery.year"
              type="year"
              placeholder="请选择年份"
              style="width: 200px"
              format="YYYY"
              value-format="YYYY"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" plain @click="getCheckList">查询</el-button>
            <el-button @click="resetCheckQuery" plain>重置</el-button>
            <el-button type="primary" icon="Plus" @click="openCheckDialog"
              >新增</el-button
            >
          </el-form-item>
        </el-form>
        <!-- 新增按钮 -->

        <!-- 容量电费列表 -->
        <el-table :data="checkList" border style="margin-bottom: 10px">
          <el-table-column prop="zt" label="载体" align="center" />
          <el-table-column prop="nf" label="年份" align="center" />
          <el-table-column prop="yf" label="月份" align="center" />
          <el-table-column prop="checkValue" label="容量电费" align="center" />
          <el-table-column prop="ztValue" label="载体电费" align="center" />
          <el-table-column prop="ratio" label="系数" align="center" />
        </el-table>
        <pagination
          v-show="checkTotal > 0"
          :total="checkTotal"
          v-model:page="checkQuery.pageNum"
          v-model:limit="checkQuery.pageSize"
          @pagination="getCheckList"
        />
        <!-- 新增容量电费弹窗 -->
        <el-dialog
          title="生成容量费"
          v-model="checkDialogVisible"
          width="700px"
          append-to-body
        >
          <el-form
            :model="checkForm"
            :rules="checkRules"
            ref="checkFormRef"
            label-width="100px"
          >
            <el-form-item label="年月" prop="month">
              <el-date-picker
                v-model="checkForm.month"
                type="month"
                value-format="YYYY-MM"
                placeholder="请选择年月"
                style="width: 600px"
                @change="handleCheckMonthChange"
              />
            </el-form-item>
            <el-form-item label="载体电费" prop="ztValue">
              <el-input v-model="checkForm.ztValue" disabled placeholder="请先选择年月" />
            </el-form-item>
            <el-form-item label="容量电费" prop="checkValue">
              <el-input
                v-model="checkForm.checkValue"
                type="number"
                @input="calcCheckRatio"
                placeholder="请输入本月容量电费"
              />
            </el-form-item>
            <el-form-item label="系数" prop="ratio" placeholder="容量电费/载体电费">
              <el-input v-model="checkForm.ratio" disabled />
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="checkDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitCheckForm">下一步</el-button>
          </template>
        </el-dialog>
        <!-- 下一步按钮 -->
        <div style="text-align: right; margin-top: 20px">
          <el-button type="primary" @click="goStep2" :disabled="!canGoStep2"
            >下一步</el-button
          >
        </div>
      </div>

      <!-- 步骤二：确认客户应收 -->
      <div v-show="activeStep === 1">
        <el-card>
          <div style="margin-bottom: 10px">
            <span>待确认客户容量费用列表（{{ confirmMonth }}）</span>
          </div>
          <el-table :data="zhFeeList" border>
            <el-table-column prop="qymc" label="租户名称" align="center" width="320" />
            <el-table-column prop="zt" label="载体" align="center" />
            <el-table-column prop="nf" label="年份" align="center" />
            <el-table-column prop="yf" label="月份" align="center" />
            <el-table-column prop="dbyt" label="状态" align="center" />
            <el-table-column prop="hklx" label="费用类型" align="center" />
            <el-table-column prop="zdf" label="容量费" align="center" />
          </el-table>
          <pagination
            v-show="zhFeeTotal > 0"
            :total="zhFeeTotal"
            v-model:page="zhFeeQuery.pageNum"
            v-model:limit="zhFeeQuery.pageSize"
            @pagination="getZhFeeList"
          />
          <div style="text-align: right; margin-top: 20px">
            <el-button @click="activeStep = 0">上一步</el-button>
            <el-button type="primary" @click="confirmZhFeeList"
              >确认{{ confirmMonth }}客户应收容量费</el-button
            >
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { parseTime } from "@/utils/ruoyi.js";
import { getCarrierEnergy, getCheckEnergyList, addCheckEnergy } from "@/api/energy/check";
import { useRouter,useRoute } from "vue-router";
const route = useRoute();
const router = useRouter();
import { selectZhFeeList, confirmZhFee } from "@/api/carrier/ammeter";
const nr = route.query.nr || ""; // 路由中的nr
const { proxy } = getCurrentInstance();

const activeStep = ref(0);

// 步骤一相关
const checkList = ref([]);
const checkTotal = ref(0);
const checkQuery = reactive({
  year: getYearStr(),
  month: getLastMonthStr(),
  zt: nr, // 直接用路由nr
  pageNum: 1,
  pageSize: 10,
});

const checkDialogVisible = ref(false);
const checkForm = reactive({
  zt: nr, // 直接用路由nr
  month: "",
  ztValue: "",
  checkValue: "",
  ratio: "",
});
const checkRules = {
  month: [{ required: true, message: "请选择年月", trigger: "change" }],
  ztValue: [{ required: true, message: "请获取载体电费", trigger: "change" }],
  checkValue: [{ required: true, message: "请输入容量电费", trigger: "blur" }],
  ratio: [{ required: true, message: "请输入系数", trigger: "change" }],
};
const checkFormRef = ref();

function getYearStr() {
  const d = new Date();
  return `${d.getFullYear()}`;
}
function getLastMonthStr() {
  const d = new Date();
  d.setDate(1); // 设置为当月第一天
  d.setMonth(d.getMonth() - 1);

  console.log(parseTime(d, "{y}-{m}"),parseTime(d),d.getMonth());
  return parseTime(d, "{y}-{m}");
}

function getCheckList() {
  getCheckEnergyList({ ...checkQuery }).then((res) => {
    let getList = (res.data?.list || []).map((item) => {
      return {
        ...item,
        month: parseTime(item.month, "{y}-{m}"),
        ratio: item.ztValue ? (item.checkValue / item.ztValue).toFixed(4) : "",
      };
    });
    checkList.value = getList;
    checkTotal.value = res.data?.total || 0;
  });
}
function resetCheckQuery() {
  checkQuery.month = getLastMonthStr();
  checkQuery.pageNum = 1;
  checkQuery.pageSize = 10;
  getCheckList();
}

function openCheckDialog() {
  checkForm.zt = nr; // 始终用路由nr
  checkForm.month = "";
  checkForm.ztValue = "";
  checkForm.checkValue = "";
  checkForm.ratio = "";
  checkDialogVisible.value = true;
}

function handleCheckMonthChange() {
  fetchZtValue();
}
function fetchZtValue() {
  if (checkForm.zt && checkForm.month) {
    getCarrierEnergy({ zt: checkForm.zt, month: checkForm.month }).then((res) => {
      checkForm.ztValue = res.data || "";
      calcCheckRatio();
    });
  } else {
    checkForm.ztValue = "";
    checkForm.ratio = "";
  }
}
function calcCheckRatio() {
  const ztValue = parseFloat(checkForm.ztValue);
  const checkValue = parseFloat(checkForm.checkValue);
  if (ztValue && checkValue) {
    checkForm.ratio = (checkValue / ztValue).toFixed(4);
  } else {
    checkForm.ratio = "";
  }
}
function submitCheckForm() {
  checkFormRef.value.validate((valid) => {
    if (!valid) return;
    addCheckEnergy({ ...checkForm }).then((res) => {
      if (res.code === 200) {
        checkDialogVisible.value = false;
        getCheckList();
      }
    });
  });
}

// 步骤二相关
const zhFeeList = ref([]);
const zhFeeTotal = ref(0);
const zhFeeQuery = reactive({
  dflx: 2,
  zt: nr,
  pageNum: 1,
  pageSize: 10,
});
const confirmMonth = ref("");

const canGoStep2 = computed(() => checkList.value.length > 0);

function goStep2() {
  // 默认取最新一条的月份
  if (checkList.value.length > 0) {
    confirmMonth.value =
      `${checkList.value[0].nf}-${
        checkList.value[0].yf >= 10 ? checkList.value[0].yf : "0" + checkList.value[0].yf
      }` || "";
    zhFeeQuery.pageNum = 1;
    zhFeeQuery.pageSize = 10;
    getZhFeeList();
    activeStep.value = 1;
  }
}

function getZhFeeList() {
  selectZhFeeList({
    ...zhFeeQuery,
    month: confirmMonth.value,
  }).then((res) => {
    zhFeeList.value = res.data?.list || [];
    zhFeeTotal.value = res.data?.total || 0;
  });
}

function confirmZhFeeList() {
  confirmZhFee({
    dflx: 2,
    zt: nr,
    date: confirmMonth.value,
  }).then((res) => {
    if (res.code === 200) {
      proxy.$modal.msgSuccess(res.msg || "客户电费确认成功");
      // activeStep.value = 0;
      // getCheckList();

      router.back();
    }
  });
}

onMounted(() => {
  getCheckList();
});
</script>

<style scoped>
.created-check-bill {
  /* 样式区域 */
}
</style>
